import axios from 'axios'
import { setToken, getToken, mergeConfigObjects } from '@/libs/util'
// import { Message } from 'iview'
class HttpRequest {
	constructor(baseUrl) {
		this.baseUrl = baseUrl
		this.queue = {}
	}
	getInsideConfig() {
		const config = {
			baseURL: this.baseUrl,
			headers: {
				Authorization: getToken()
			}
		}
		return config
	}
	destroy(url) {
		delete this.queue[url]
		if (!Object.keys(this.queue).length) {
			// Spin.hide()
		}
	}
	interceptors(instance, url) {
		// 请求拦截
		instance.interceptors.request.use(
			(config) => {
				// 添加全局的loading...
				if (!Object.keys(this.queue).length) {
					// Spin.show() // 不建议开启，因为界面不友好
				}
				this.queue[url] = true
				return config
			},
			(error) => {
				return Promise.reject(error)
			}
		)
		// 响应拦截
		instance.interceptors.response.use(
			(res) => {
				this.destroy(url)
				const { data, status } = res
				return { data, status }
			},
			(error) => {
				this.destroy(url)
				if (error.response && error.response.status === 401) {
					setToken(null)
				}
				return Promise.reject(error)
			}
		)
	}
	request(options) {
		const instance = axios.create()
		const defaultOptions = this.getInsideConfig()
		options = mergeConfigObjects(options, defaultOptions)
		this.interceptors(instance, options.url)
		return instance(options)
	}
}
export default HttpRequest
